package com.example.recordingpen_datacollection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.recordingpen_datacollection.Utils.EncryptionUtils;
import com.example.recordingpen_datacollection.Utils.HtmlLayoutUtil.BDHtmlLayoutV2Util;
import com.example.recordingpen_datacollection.entity.DosageStatistics;
import com.example.recordingpen_datacollection.entity.GetdosSta;
import com.example.recordingpen_datacollection.entity.Query.GetdosStaQue;
import com.example.recordingpen_datacollection.entity.Vo.ResHtmlVo;
import com.example.recordingpen_datacollection.mapper.GetdosStaMapper;
import com.example.recordingpen_datacollection.result.RLIST;
import com.example.recordingpen_datacollection.service.DosageStatisticsService;
import com.example.recordingpen_datacollection.service.GetdosStaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xg
 * @since 2024-09-02
 */
@Service
public class GetdosStaServiceImpl extends ServiceImpl<GetdosStaMapper, GetdosSta> implements GetdosStaService {
    @Autowired
    private DosageStatisticsService dosageStatisticsService;

    @Override
    public RLIST getDosstaPage(GetdosStaQue getdosStaQue, Integer value) {
        QueryWrapper wrapper = new QueryWrapper();
        if(value != null && value > 0){
            wrapper.eq("login_id",value);
        }
        wrapper.orderByDesc("uaddtime");
        Page<GetdosSta> page = new Page<>(getdosStaQue.getPageNo(), getdosStaQue.getPageSize());
        this.page(page, wrapper);
        long total = page.getTotal();
        List<GetdosSta> list = page.getRecords();

        long numPage = 0;
        if(total == 0){
            numPage = 1L;
        } else if(list.size() == 0){
            numPage = 1L;
        } else {
            // 每页条数
            numPage = (long) Math.ceil(total / (double)getdosStaQue.getPageSize()) ;
        }
        if(list.size() == 0){
            return RLIST.error().message("暂无数据") ;
        }
        return RLIST.ok().data("data",list).data("total",total).data("numPage",numPage);
    }

    @Override
    public RLIST getResHtml(ResHtmlVo resHtmlVo) {
        Integer id = resHtmlVo.getId();
        Integer serverType = resHtmlVo.getServerType();
        boolean format = resHtmlVo.isFormat();
        GetdosSta byId = this.getById(id);

        if(byId.getState() <=1){
            return RLIST.error().message("请等待完成");
        }
        if(byId.getFinalResult() == null || byId.getFinalResult().isEmpty()){
            DosageStatistics dosageStatistics = new DosageStatistics();
            dosageStatistics.setId(id);
            dosageStatistics.setState(0);
            dosageStatisticsService.updateById(dosageStatistics);
            return RLIST.error().message("数据异常，重新请求数据中");
        }
        if(byId.getHttpUrl()==null || byId.getHttpUrl().isEmpty()){
            String filePath = null;
            String os = System.getProperty("os.name").toLowerCase();
            if (os.startsWith("win")) {
                String htmlUrl_file="D:\\JAVAFile\\RecordingPen\\Html\\";
                String htmlUrl = htmlUrl_file+"FIlEDEV"+byId.getLoginId()+"\\";
                // 创建File对象
                File file = new File(htmlUrl);

                // 判断文件是否存在
                if (!file.exists()) {

                        // 文件不存在，创建文件
                        boolean fileCreated = file.mkdirs();
                        if (fileCreated) {
                            System.out.println("文件创建成功：" + htmlUrl);
                        } else {
                            System.out.println("文件创建失败：" + htmlUrl);
                        }

                } else {
                    System.out.println("文件已存在：" + htmlUrl);
                }
                String toHtml = new BDHtmlLayoutV2Util().convertToHtml(byId.getFinalResult());
                 filePath = htmlUrl+byId.getTextName()+".html";
                // 使用try-with-resources语句自动关闭资源
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
                    // 写入HTML内容到文件
                    writer.write(toHtml);

                    // 刷新缓冲区，确保所有数据都被写入文件（这一步在try-with-resources中是可选的，因为资源会在结束时自动关闭并刷新）
                    writer.flush();

                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("创建或写入HTML文件时发生错误。");
                }
            } else if (os.startsWith("linux")) {
                System.out.println("linux");

                String htmlUrl_file="/home/JAVAFile/RecordingPen/Html/";
                String htmlUrl = htmlUrl_file+"FIlEDEV"+byId.getLoginId()+"/";
                // 创建File对象
                File file = new File(htmlUrl);

                // 判断文件是否存在
                if (!file.exists()) {

                    // 文件不存在，创建文件
                    boolean fileCreated = file.mkdirs();
                    if (fileCreated) {
                        System.out.println("文件创建成功：" + htmlUrl);
                    } else {
                        System.out.println("文件创建失败：" + htmlUrl);
                    }

                } else {
                    System.out.println("文件已存在：" + htmlUrl);
                }
                String toHtml = new BDHtmlLayoutV2Util().convertToHtml(byId.getFinalResult());
                filePath = htmlUrl+byId.getTextName()+".html";
                // 使用try-with-resources语句自动关闭资源
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
                    // 写入HTML内容到文件
                    writer.write(toHtml);

                    // 刷新缓冲区，确保所有数据都被写入文件（这一步在try-with-resources中是可选的，因为资源会在结束时自动关闭并刷新）
                    writer.flush();

                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("创建或写入HTML文件时发生错误。");
                }

            } else {
                System.out.println("Unknown");
            }

            DosageStatistics dosageStatistics = new DosageStatistics();
            dosageStatistics.setId(id);
            dosageStatistics.setHttpUrl(filePath);
            dosageStatisticsService.updateById(dosageStatistics);
        }
        String encrypt = EncryptionUtils.encrypt(String.valueOf(byId.getId()));
        //http://localhost:10487/getdos-sta/player?file=HnbBoMHH3HlW4xBOvprCjQ==
        String http = "http://localhost:10487/getdos-sta/player?file="+encrypt;
            if((serverType == 5 || serverType ==4) && format){
                return RLIST.ok().data("data",new BDHtmlLayoutV2Util().convertToHtml(byId.getFinalResult())).data("htmlUrl",http);

            }
            return RLIST.ok().data("data",byId.getFinalResult()).data("htmlUrl",http);


    }


}
